package awk.aio3;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Future;

public class Client {
    public static void main(String[] args) throws Exception {
        AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
        //这里Client类没有实现 implements CompletionHandler<Void, AsyncTimeClient>, Runnable 接口
        //connect 使用future方式
        Future<Void> future = client.connect(new InetSocketAddress("127.0.0.1", 8013));
        //Future 返回 null 表示连接成功
        ByteBuffer buffer = ByteBuffer.allocate(8192);
        //第二个参数 attachment 的类型要和第三个参数的<Integer,?> 相同,并且第三个参数的实现类的参数也要与之相同
        client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                System.out.println("client received: " + new String(buffer.array()));
            }
            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                exc.printStackTrace();
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread.sleep(10000);
    }
}
